var mongoose = require('mongoose');
var common = require('../common/common');

var date = new Date();
var UsersSchema = new mongoose.Schema({
	username : {
		unique : true,
		type : String
	},
	password : String,
	email : String,
	//最后一次登录ip
	last_login_ip:String,
	//最后一次登录时间
	last_login_time:{
		type:Number,
		default:date.getTime()
	},
	role :{
		type : Number,
		default : 0
	},
	meta:{
		createAt : {
			type : Number,
			default : date.getTime()
		},
		updateAt:{
			type : Number,
			default : date.getTime()
		}
	}
})

UsersSchema.pre('save', function(next){
	var user = this;
	if ( this.isNew ) {
		this.meta.createAt = this.meta.updateAt = Date.now();
		//对用户注册的密码进行md5加密
		user.password = common.md5( user.password );
	}else{
		this.meta.updateAt = Date.now()
	}
	next();
})

UsersSchema.statics = {
	fetch:function(cb){
		return this.find({}).exec(cb);
	},
	findById: function(where, field, cb){
		return this.findOne(where,field).exec(cb);
	}
}

module.exports= UsersSchema